/**
  ****************************(C) COPYRIGHT 2019 DJI****************************
  * @file       usb_task.c/h
  * @brief      usb outputs the error message.
  * @note       
  * @history
  *  Version    Date            Author          Modification
  *  V1.0.0     Nov-11-2019     RM              1. done
  *
  @verbatim
  ==============================================================================

  ==============================================================================
  @endverbatim
  ****************************(C) COPYRIGHT 2019 DJI****************************
  */
#include "usb_task.h"

#include "cmsis_os.h"

#include "usb_device.h"
#include "usbd_cdc_if.h"
#include <stdio.h>
#include <stdarg.h>
#include "string.h"
#include "LTC2440.h"
#include "ADS7844.h"
#include "AD7682.h"

static uint8_t usb_buf[256];

void AD7682_printf(void)
{
    static int channel_switch = 0;
    float volt;
    
    volt = read_AD7682_voltage(channel_switch);
    usb_printf("channel:%d, volt:%f, overflow: %d",
        channel_switch,volt,get_AD7682_overflow());
    channel_switch ++;
    channel_switch %= 4;
}

void LTC2440_printf(void)
{
    float volt;
    volt = read_LTC2440_voltage();
    usb_printf("LTC2440 read: %f",volt);
}

void ADS7844_printf(void)
{
    float volt;
    static uint8_t choice=0;

    volt = read_ADS7844_voltage(choice);
    usb_printf("ADS7844 read channnel %d : %f, overflow: %d",choice,volt,get_ADS7844_overflow());
    choice++;
    choice%=8;
}



void time_testbench(void)
{
    uint32_t start,end,i;
    start =  HAL_GetTick ();
    // for(i=0;i<1000;i++)
    // {
    //     read_AD7682_voltage(0);
    // }
    for(i=0;i<20000;i++)
    {
        read_ADS7844_voltage(0);
    }
    end = HAL_GetTick();
    usb_printf("Time used: %d ms",end - start);
}

void usb_task(void const * argument)
{
    MX_USB_DEVICE_Init();
    while(1)
    {
        osDelay(100);
        // LTC2440_printf();
        ADS7844_printf();
        // AD7682_printf();
        // time_testbench();
        // usb_printf("Time");
    }
}

void usb_printf(const char *fmt,...)
{
    static va_list ap;
    uint16_t len = 0;

    va_start(ap, fmt);

    len = vsprintf((char *)usb_buf, fmt, ap);

    va_end(ap);


    CDC_Transmit_FS(usb_buf, len);
}
